layui.define(['jquery', 'uploadFile','uploadImg', 'layedit'], function (exports) {
    var $ = layui.jquery;
    var urlTitle = 'http://cloa.oss-cn-shenzhen.aliyuncs.com/';
    var imgOssUrl = 'editImg/';
    var comp = {
        init: function (id, str) {

            var editIndex = layui.layedit.build(id);
            //console.log(editIndex)
            var content = str.replace(/onclick=['"]([^'"]+['"])/gi, '');
            var newDate = Date.parse(new Date())/1000;
            var txt = content.replace(/<img /gi, '<img onclick="window.parent.layui.areaEdit.getImg(this,' + editIndex + ')" ');
            if (txt) {
                layui.layedit.setContent(editIndex, txt, true)
            }
            $($("#" + id).next().find('input[type="file"]')[0]).attr("data", editIndex)
            $(".layui-layedit-tool input[type='file']").off("change").on("change", function (e) {
                layui.uploadImg.upload(imgOssUrl+newDate+e.target.files[0].name, e.target.files[0], 1).then(function (url) {
                    component.imgDialog({url: urlTitle+url}, layui.areaEdit.sureEdit, $(e.target).attr('data'));
                    $(".layui-layedit-tool input[type='file']").val('');
                });
            })
            return editIndex
        },
        getImg: function (e, index) {
            component.imgDialog({
                url: $(e).attr("src"),
                w: $(e).css("width"),
                h: $(e).css("height"),
                alt: $(e).attr("alt"),
                elem: e
            }, layui.areaEdit.sureEdit, index);
        },
        sureEdit: function (obj, elem, editIndex) {
            obj.w = obj.w ? obj.w : 'auto'
            obj.h = obj.h ? obj.h : 'auto'
            obj.alt = obj.alt ? obj.alt : ''
            if (elem) {
                if (obj.url) {
                    $(elem).attr("src", obj.url)
                    $(elem).css("height", obj.h)
                    $(elem).css("width", obj.w)
                    $(elem).attr("alt", obj.alt)
                }
            } else {
                if (obj.url) {
                    layui.layedit.inserImg(editIndex, "<img src='" + obj.url + "' alt='" + obj.alt + "' height='" + obj.h + "px' width='" + obj.w + "px' onclick='window.parent.layui.areaEdit.getImg(this)' />")
                }
            }
        },
    }
    exports('areaEdit', comp);
});
